<template>
  <h3>{{ eidtId ? "编辑" : "新建" }}分类</h3>
  <div class="createClass">
    <el-form
      :inline="true"
      :model="category.categoryMsg"
      class="demo-form-inline"
      @submit="() => false"
    >
      <el-form-item>
        <el-select
          v-model="category.categoryMsg.parent"
          class="m-2"
          placeholder="Select"
          size="large"
        >
          <el-option
            v-for="item in category.parent"
            :key="item._id"
            :value="item._id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类名">
        <el-input
          v-model="category.categoryMsg.name"
          placeholder="请输入分类名"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit"
          >{{ eidtId ? "更新" : "创建" }}分类</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeMount, reactive } from "vue";
import {
  creatCategory,
  getEditMsg,
  upDateCategory,
  getCreatCategory,
} from "@/api/getCategory";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
//分类信息
const category = reactive({
  categoryMsg: {
    name: "",
    parent: "",
  },
  //父级信息
  parent: <any>[],
});

const router = useRouter();
const route = useRoute();

const eidtId = computed(() => {
  return route.params.id;
});
//提交分类信息
const onSubmit = async () => {
  let result;
  if (route.params.id) {
    //更新分类数据
    result = await upDateCategory(eidtId.value, category.categoryMsg);
  } else {
    //添加分类
    result = await creatCategory(category.categoryMsg);
  }

  if (result.status === 200) {
    router.push({
      path: "/home/categoryList",
    });
    //消息提示框
    ElMessage({
      message: "保存成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "保存失败",
      type: "warning",
    });
  }
};

//获取被编辑数据的详情
const getEdit = async () => {
  let result = await getEditMsg(eidtId.value);

  if (result.status === 200) {
    category.categoryMsg.name = result.data.name;
  }
};

//获取父级下拉列表框数据
const getParent = async () => {
  let result = await getCreatCategory();

  if (result.status === 200) {
    category.parent = result.data;
  }
};

onBeforeMount(() => {
  getParent();
  if (route.params.id) getEdit();
});
</script>

<style lang="less" scoped>
.createClass {
  margin: 20px 20px 0 20px;
}
</style>
